package com.choudou5.solr.web.handler.api;

import com.choudou5.solr.api.ApiConfig;
import com.choudou5.solr.api.SearchApi;
import com.choudou5.solr.bean.common.PageBean;
import com.choudou5.solr.bean.common.PageResult;
import com.choudou5.solr.bean.common.SolrQueryParam;
import com.choudou5.solr.core.util.SolrHelper;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.constants.SolrModuleEnum;
import com.choudou5.solr.framework.util.PageJumpUtil;
import com.choudou5.solr.framework.util.RequestUtil;
import com.choudou5.solr.searchrule.SolrQueryRuleService;
import com.choudou5.solr.service.ServiceHelper;
import com.choudou5.solr.service.SolrElevateService;
import com.choudou5.solr.service.biz.BizDataService;
import com.choudou5.solr.util.SolrJUtil;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.utils.QueryBuilder;
import com.choudou5.solr.utils.SolrQueryBuilder;
import com.choudou5.solr.web.handler.BaseHandler;
import com.choudou5.spider.service.SpiderService;
import org.apache.commons.collections.MapUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name 问题库 API
 * @author choudou5
 * @date 2018-08-06
 */
public class QaApiHandler extends BaseHandler {

    private final SearchApi searchApi = SearchApi.getInstance();

    private final SolrElevateService solrElevateService = ServiceHelper.singleton(SolrElevateService.class);
    private static BizDataService bizDataService = ServiceHelper.singleton(BizDataService.class);

    @Override
    public void execute(String bizMethod, HttpServletRequest req, HttpServletResponse resp) {
        logger.info("QaApiHandler bizMethod:{}", bizMethod);
        switch (bizMethod){
            case "search":
                search(req, resp);
                break;
            case "searchFromSE":
                searchFromSE(req, resp);
                break;
            case "hit":
                hit(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "synCategoryData":
                synCategoryData(req, resp);
                break;
            default:
                PageJumpUtil.errorOut(ErrorResp.Not_Found, req, resp);
                break;
        }
    }


    /**
     * 搜索
     * @param req
     * @param resp
     */
    private void search(HttpServletRequest req, HttpServletResponse resp){
        String queryStr = RequestUtil.getStrParameterUnescapeJava(req, ApiConfig.PARAM_QUERY);
        String categoryId = RequestUtil.getStrParameter(req, "firstCategoryId");
        PageBean pageBean = QueryBuilder.buildPageBean(req);
        SolrQueryParam queryParam = SolrQueryRuleService.getQueryRule(ApiConfig.API_QA, queryStr, pageBean);
        //追加过滤条件
        SolrQueryBuilder.appendFilterQuery(queryParam, "firstCategoryId", categoryId);
        PageResult pageResult = searchApi.searchPage(queryParam);
        PageJumpUtil.writeJsonObjOk(pageResult, resp);
    }


    private void add(HttpServletRequest req, HttpServletResponse resp){
//        问题、回复、问答 ID、问答分类 ID、问答1级分类 ID
        Map<String, Object> inputMap = buildMap(req);
        inputMap.remove(ApiConfig.PARAM_AK);
        inputMap.remove(ApiConfig.PARAM_API);
        if(MapUtils.isEmpty(inputMap)){
            PageJumpUtil.errorOut(ErrorResp.INVALID_PARAM, "表单无数据", req, resp);
            return;
        }
        if(validParam(req, resp, inputMap, new String[]{"id", "categoryId", "firstCategoryId", "question", "answer"})){
            //添加数据
            SolrJUtil.add(inputMap, SolrHelper.getCore(ApiConfig.API_QA));
            PageJumpUtil.writeJsonOk("保存成功", resp);
        }
    }


    /**
     * 供solr学习和提升搜索精准度。
     * @param req
     * @param resp
     */
    private void hit(HttpServletRequest req, HttpServletResponse resp){
        String id = RequestUtil.getStrParameter(req, ApiConfig.PARAM_ID);
        String queryStr = RequestUtil.getStrParameterUnescapeJava(req, ApiConfig.PARAM_QUERY);
        if(validParam(req, resp, new Object[]{id, queryStr}, new String[]{"id参数", "query参数"})){
            solrElevateService.save(SolrModuleEnum.getDefKey(), queryStr, id);
            PageJumpUtil.writeJsonOk("ok", resp);
        }
    }

    /**
     * 基于第三方搜索引擎 搜索
     * @param req
     * @param resp
     */
    private void searchFromSE(HttpServletRequest req, HttpServletResponse resp){
        String queryStr = RequestUtil.getStrParameterUnescapeJava(req, ApiConfig.PARAM_QUERY);
        String seTypes = RequestUtil.getStrParameter(req, "seTypes");
        if(validParam(req, resp, new Object[]{seTypes}, new String[]{"参数seTypes"})){
            String[] seTypeArray = StrUtil.split(seTypes, ",");
            Map<String, List> map = new HashMap<>();
            for (String seType : seTypeArray) {
                map.put(seType, SpiderService.pageCrawl(seType, queryStr));
            }
            PageJumpUtil.writeJsonObjOk(map, resp);
        }
    }


    /**
     * 同步分类数据
     * @param req
     * @param resp
     */
    private void synCategoryData(HttpServletRequest req, HttpServletResponse resp){
        String data = RequestUtil.getStrParameter(req, "data");
        if(validParam(req, resp, new Object[]{data}, new String[]{"参数data"})){
            bizDataService.updateBizData("qa_category_list", "问题库分类", data);
            PageJumpUtil.writeJsonOk("同步成功", resp);
        }
    }
}
